#include "TeamSelectionMenu.h"
#include "Utilities.h"
#include "PrintUtilities.h"
#include "UserManager.h"
#include "LeagueManager.h"
#include "MenuManager.h"
#include "GameSettings.h"
#include "League.h"

#include <algorithm>

TeamSelectionMenu::TeamSelectionMenu(MenuManager* const i_menuManager)
	: Menu(i_menuManager)
	, m_freeTeam(true)
	, m_currentUser(0)
{
}

void TeamSelectionMenu::Draw() const
{
	std::cout << Print::Title("TEAM SELECTION:") << std::endl;

	size_t count = 0;

	std::cout << " \tLEAGUE:" << std::string(League::MAX_LEAGUE_NAME_SIZE - 7, ' ') << "\tPOWER:\tNAME:" << std::endl;
	
	static const size_t max_char_team_name = GetSP()->GetSettings().GetValue("I_MAX_CHAR_TEAM_NAME").Get<size_t>();

	const LeagueVec& leagues = GetSP()->GetLeagueMgr().GetLeagues(true);
	for(LeagueVecCit it  = leagues.begin(); it != leagues.end(); ++it)
	{
		const TeamVec& teams = (*it)->GetTeams();
		for(TeamVecCit teamIt = teams.begin(); teamIt != teams.end(); ++teamIt)
		{
			std::cout	
				<< ++count << ")\t"
				<< (*it)->GetName() << "\t"
				<< (*teamIt)->GetTeamPower() << "\t"
				<< Print::TabUpTo((*teamIt)->GetName(), max_char_team_name)
				<< (((*teamIt)->IsUserControlled()) ? "**SELECTED**" : "")
				<< std::endl;
		}
		
		std::cout << std::endl;
	}
	
	const UsersList& users = GetSP()->GetUserMgr().GetUserList();
	std::string temp = "(1-" + Utilities::IntToString(count) + ") Choose the team.\n";
	std::cout	<< Print::Options(temp)
				<< users.at(m_currentUser)->m_name <<" selection: ";
	
	if (!m_freeTeam)
	{
		std::cout << "Team already busy!...\nSelection: ";
	}
}


bool TeamSelectionMenu::Input(const std::string& i_input)
{
	bool goodInput = true;

	size_t res = Utilities::StringToInt(i_input);

	LeagueVec& leagues = GetSP()->GetLeagueMgr().GetLeagues(true);

	size_t numberOfTeams = 0;

	for (LeagueVecIt it = leagues.begin(); it != leagues.end(); ++it)
		numberOfTeams += (*it)->GetSettings().numOfTeams;

	if (res <= 0 || res > numberOfTeams)
		return false;

	Team* team = 0;
	for (LeagueVecIt it = leagues.begin(); it != leagues.end(); ++it)
	{
		if (res > (*it)->GetSettings().numOfTeams)
			res -= (*it)->GetSettings().numOfTeams;
		else
		{
			team = (*it)->GetTeams()[res - 1];
			break;
		}
	}

	const UsersList& users = GetSP()->GetUserMgr().GetUserList();
	
	//find if is already busy
	if(std::find_if(users.begin(), users.end(), CompareUserTeamPtr(team)) != users.end())
	{
		goodInput = false;
		m_freeTeam = false;
	}
	else
	{
		users.at(m_currentUser)->m_team = team;
		users.at(m_currentUser)->m_team->SetUserControlled(true);
		m_freeTeam = true;
		++m_currentUser;
	}

	if (m_currentUser == users.size())
	{
		m_freeTeam = true;
		m_currentUser = 0;
		GetMM()->SetMenu(GetMM()->GetMainMenu());
	}
	else
		goodInput = false;

	return goodInput;
}